package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeServrce;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeServrce employeeServrce;

   //登录
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        log.info("用户登录:{}",employee);

       //1.调用业务层验证用户登录的方法
        //具体的登录的业务逻辑在业务层方法中
        Map map = employeeServrce.checkLogin(employee);
        Object enp = map.get("emp");

        //2.返回登录结果
        if (enp == null){
            return R.error((String) map.get("msg"));
        }
        //登录成后，将信息存储进Seesion之中
        session.setAttribute("employee",enp);
        return R.success(employee);
    }

    //退出
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){


        //清理Sesion中保存的当前登录员工的id
        request.getSession().removeAttribute("/employee");
        return R.success("退出成功");
    }

    //新增
    @PostMapping
    public R<String> addemp(HttpServletRequest request , @RequestBody Employee employee){
        //设置初始密码并且加密
        employee.setPassword(DigestUtils.md5DigestAsHex("12345".getBytes()));

        //时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //ID
        Employee empID = (Employee) request.getSession().getAttribute("employee");
        Long id = empID.getId();
        employee.setCreateUser(id);
        employee.setUpdateUser(id);

        //
        employeeServrce.save(employee);
        return R.success("新增成功");
    }


    //分页查询and模糊查询
    @GetMapping ("/page")
    public R Seclect(@RequestParam Map map){
        //调用业务层，查询分页数据
        IPage<Employee> employeeIPage = employeeServrce.querypage(map);
        //封装并返回查询结果数据
        return R.success(employeeIPage);
    }




    //修改
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());

        Employee empID = (Employee) request.getSession().getAttribute("employee");
        Long id = empID.getId();

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(id);
        employeeServrce.updateById(employee);

        return R.success("员工信息修改成功");
    }

}
